<?php
/**
 * PHPECS社交电商系统，使用thinkphp框架+MySQL数据库编写的小程序商城系统，基于LGPL协议开源授权
 * @package phpecs
 * @author qq(123865789)
 * @copyright 2018-2020 深圳塔灯网络科技有限公司
 * @version 2.0
 * @license http://www.phpecs.com/lgpl.html phpecs开源授权协议：GNU Lesser General Public License
 **/
namespace app\hgapi\controller;
use app\hgapi\model\activity\ActivityRecharge;
use app\hgapi\model\store\StoreProductCoupon;
use app\hgapi\model\store\StoreProductImg;
use app\hgapi\model\store\StoreProduct;
use app\hgapi\model\store\StoreOrder;
use app\hgapi\model\store\StoreOrderList;
use app\hgapi\model\activity\Activity;
use app\hgapi\model\system\Banner;
use app\hgapi\model\system\Foot;
use app\hgapi\model\system\Help;
use app\hgapi\model\system\HelpCategory;
use app\hgapi\model\system\Link;
use app\hgapi\model\system\Message;
use app\hgapi\model\system\Page;
use app\hgapi\model\system\Popup;
use app\hgapi\model\system\PopupRecord;
use app\hgapi\model\system\Site;
use app\hgapi\model\goods\GoodsGift;
use app\hgapi\model\goods\GoodsPackage;
use app\hgapi\model\user\UserPackage;
use app\hgapi\model\user\User;

class PublicApi extends Auth{

    /**
     * 首页信息
     */
    public function home_info(){
        //banner
        $banner = Banner::selBanner(['status' =>  1], 'img, link, link_column');
        //logo和广告
        $ad = Site::getSite('logo, ad, gong');
        //首页区块

        $qu = Foot::selFoot(['status' => 1]);
        //优惠券
        $newCoupon = []; //商品能使用的优惠券
        //查出所有优惠券
        $coupon = StoreProductCoupon::selCoupon(['status' => 1]);
        foreach ($coupon as $k => $v){
            $valid = explode(' - ', $v['valid']);
            $start = strtotime($valid[0]);
            $end = strtotime($valid[1]);
            if ($v['term'] == 1 || ($v['term'] == 0 && time() > $start && time() < $end)){
                if ($v['apply'] == 0){
                    array_push($newCoupon, $coupon[$k]);
                }
            }
        }
        //查出首页链接
        $link = Link::selLink(['status' => 1]);
        //查出活动链接
        $activity = Activity::selActivity(['status' => 1], 3);
        $result = array('banner' => $banner, 'ad' => $ad, 'qu' => $qu, 'coupon' => $newCoupon, 'link' => $link, 'activity' => $activity);
        successCode($result);
    }

    /**
     * 查看大礼包下面的礼品
     */
    public function cha_lipin(){
        $id = input('id'); //大礼包id
        $uid = input('uid'); //用户id
        //查询我的所有大礼包
        $package = UserPackage::getField(['uid' => $uid], 'package');
        $package = explode(',', $package);
        if (in_array($id, $package)){
            $is = 1;
        }else{
            $is = 0;
        }
        //查询大礼包下面的礼品
        $gid = GoodsPackage::getField(['id' => $id], 'gid');
        $gids = explode(',', $gid);
        $list = GoodsGift::selGift(['id' => ['in', $gids]]);
        foreach ($list as $k => $v){
            $list[$k]['index'] = numToWord($k+1);
        }
        successCode(['list' => $list, 'info' => $is]);
    }

    /**
     * 用户扫码确认领取添加领取详情
     */
    public function add_package(){
        $id = input('id'); //大礼包id
        $uid = input('uid'); //用户id
        $yid = input('yid'); //引流商家id
        $formId = input('formId'); //引流商家id
        $add = [
            'uid' => $uid,
            'package' => $id,
            'yid' => $yid,
            'formId' => $formId
        ];
        $re = UserPackage::add($add);
        if ($re){
            successCode('领取成功');
        }else{
            errorCode('已领取过大礼包');
        }
    }

    /**
     * 发送模板消息
     */
    public function template(){
        $openid = input('openid'); //用户openid
        $prepay_id = input('prepay_id'); //支付会话
        $oid = input('oid'); //相关订单id
        $type = input('type');
        switch ($type){
            case '1':
                //订单支付
                $find = StoreOrder::getOrder(['id' => $oid], 'id, order, time, money, price, benefit, freight');
                //查询商品信息
                $count = StoreOrderList::countOrderList(['oid' => $find['id']]);
                $name = StoreOrderList::valueName($find['id']);
                if ($count > 1){ //多件商品
                    $shop_info = $name . '等' . $count . '件商品';
                }else{
                    $shop_info = $name;
                }
                $time = date('Y-m-d H:i:s', $find['time']);
                if ($find['freight'] > 0 && $find['freight']){
                    $price = $find['price'] . '元(运费'. $find['freight'] .'元)';
                }else{
                    $price = $find['price'] . '元';
                }
                if ($find['benefit']){
                    $freight = '优惠' . $find['benefit'] . '元';
                    $shi = ($find['money'] - $find['benefit']) <= 0 ? '0.00元' : ($find['money'] - $find['benefit']) . '元';
                }else{
                    $freight = '无优惠';
                    $shi = $find['money'] . '元';
                }
                template(11, $openid, $prepay_id, [$find['order'], $shop_info, $time, $price, $freight, $shi, '待发货', '交易成功']);
                break;
            case '2':
                //购买打卡支付
                $find = StoreOrder::getOrderClock($oid);
                $start = $find['h_time'] + 3600 * 24;
                $end = $start + 3600 * 24 * ($find['tian'] - 1);
                $shijian = date('Y年m月d号', $start) . ' - ' . date('Y年m月d号', $end);
                if ($find['rule'] == 1) {
                    $msg = $shijian . '每天7-8点打卡签到成功商品免费领';
                } else if ($find['rule'] == 2) {
                    $msg = $shijian . '每天20-21点打卡签到成功商品免费领';
                } else if ($find['rule'] == 3) {
                    $msg = $shijian . '每天7-8点&20-21点打卡签到成功商品免费领';
                }
                template(14, $openid, $prepay_id, [$find['name'], $shijian, $msg]);
                break;
            case '3':
                //打卡签到
                $find = StoreOrder::getOrderClock($oid);
                $start = $find['h_time'] + 3600 * 24;
                $end = $start + 3600 * 24 * ($find['tian'] - 1);
                $shijian = date('Y年m月d号', $start) . ' - ' . date('Y年m月d号', $end);
                if ($find['rule'] == 1) {
                    $msg = $shijian . '每天7-8点打卡签到成功商品免费领';
                } else if ($find['rule'] == 2) {
                    $msg = $shijian . '每天20-21点打卡签到成功商品免费领';
                } else if ($find['rule'] == 3) {
                    $msg = $shijian . '每天7-8点&20-21点打卡签到成功商品免费领';
                }
                template(6, $openid, $prepay_id, [$find['name'], $msg, '您已经成功完成任务，您的商品即将发货，商品购买费用将退回到佣金，你可以在佣金处提现，详情查看']);
        }
    }

    /**
     * 帮助中心
     */
    public function help(){
        $cate = HelpCategory::selHelpCategory(['status' => 1]);
        //顺便查出一个栏目下的十条数据
        //判断提交过来的分类有没有下级
        $all = HelpCategory::columnField(['pid' => $cate[0]['id']], 'id');
        array_unshift($all, $cate[0]['id']);
        $help = Help::selHelp(['cid' => ['in', $all]], '', 10);
        foreach ($help as $k => $v){
            $help[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
        }
        successCode(['cate' => $cate, 'help' => $help]);
    }

    /**
     * 帮助详情
     */
    public function help_operate(){
        $id = input('id');
        $data = Help::getHelp(['id' => $id]);
        successCode($data);
    }

    /**
     * 查询当前分类下的数据
     */
    public function help_lower(){
        $cid = input('cid');
        $start = input('start');
        $limit = input('limit');
        $all = HelpCategory::columnField(['pid' => $cid], 'id');
        array_unshift($all, $cid);
        $help = Help::selHelp(['cid' => ['in', $all]], $start, $limit);
        foreach ($help as $k => $v){
            $help[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
        }
        successCode($help);
    }

    /**
     * 获取session
     */
    public function code2Session(){
        $secret = secret();
        $appid = $secret['appid']; //小程序id
        $secret = $secret['secret_key']; //小程序secret
        $code = input('code');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $result = file_get_contents($url);
        echo $result;
    }

    /**
     * 获取微信绑定的手机号
     */
    public function get_phone(){
        //引入解密文件
        vendor('XcxEncryp.wxBizDataCrypt');
        $secret = secret();
        $appid = $secret['appid']; //小程序id
        $sessionKey = input('session_key'); //会话session_key
        $encryptedData = input('encryptedData'); //包括敏感数据在内的完整用户信息的加密数据
        $iv = input('iv'); //加密算法的初始向量
        $openid = input('openid'); //opendi
        $pc = new \WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {
            $data = json_decode($data, true);
            User::upField(['openid' => $openid], 'phone', $data['phoneNumber']);
            successCode($data);
        } else {
            errorCode('绑定失败');
        }
    }

    /**
     * 获取充值活动
     */
    public function huo_recharge(){
        $find = ActivityRecharge::getRechargeInfo(['status' => 1, 'end' => ['gt', time()]]);
        if ($find){
            $find['time'] = date('Y-m-d', $find['start']) . ' - ' . date('Y-m-d', $find['end']);
        }
        successCode($find);
    }

    /**
     * 弹窗信息
     */
    public function popup(){
        $id = input('id'); //弹窗id
        $uid = input('uid'); //弹窗id
        $find = Popup::getPopupInfo(['id' => $id, 'status' => 1]);
        if ($find['object'] == 1){
            $order = StoreOrder::getOrder(['uid' => $uid], '');
        }
        if ($find['rate'] == 2){
            $record = PopupRecord::getPopupRecordInfo(['uid' => $uid, 'popup' => $id]);
        }
        if ($find && !$order && !$record) successCode($find);
    }

    /**
     * 弹窗记录
     */
    public function add_popup(){
        $id = input('id'); //弹窗id
        $uid = input('uid'); //用户id
        $data = [
            'uid' => $uid,
            'popup' => $id,
            'time' => time(),
        ];
        PopupRecord::add($data);
    }

    /**
     * 查出商品
     */
    public function get_shop(){
        $start = input('start');
        $limit = input('limit');
        //查询商品
        $field = 'id,name,price';
        $data = StoreProduct::selProductLimit(['status' => 0, 'type' => 0, 'is_del' => 0], $field, $start, $limit);
        foreach ($data as $k => $v){
            $data[$k]['img'] = StoreProductImg::getImg($v['id']);
        }
        successCode($data);
    }

    /**
     * 获取消息列表
     */
    public function getMessage(){
        $start = input('start');
        $limit = input('limit');
        $uid = input('uid');
        $data = Message::selMessageZhi($uid, $start, $limit);
        successCode($data);
    }
}